package com.pap.rbac.login.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pap.base.util.jackson.JacksonUtilss;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.user.IUserAgent;
import com.pap.rbac.user.auto.entity.User;

@RestController
@RequestMapping("/v1/rbac/login")
public class LoginController {

	private static Logger logger  =  LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private IUserAgent userAgent;
	
	@RequestMapping(value = "/loginbyloginname", method = {RequestMethod.POST} )
	public ResponseVO<User> loginByLoginName(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "loginJSON", required = true) String loginJSON,
			HttpServletResponse response) throws Exception {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		User inputUser = objectMapper.readValue(loginJSON, User.class);
		if(inputUser != null && StringUtilss.isNotEmpty(inputUser.getLoginName())
				&& StringUtilss.isNotEmpty(inputUser.getPasswords())) {
			Map<Object, Object> loginMap = new HashMap<Object, Object>();
			loginMap.put("loginName", inputUser.getLoginName());
			loginMap.put("passwords", inputUser.getPasswords());
			List<User> loginList = userAgent.selectListByMap(loginMap);
			if(loginList != null && loginList.size() > 0) {
				User user = loginList.get(0);
				user.setPasswords(null);
				return ResponseVO.successdata(user);
			} else {
				return ResponseVO.validfail("用户名密码错误，请检验数据!");
			}
		} else {
			return ResponseVO.validfail("用户名密码为空，请检查数据!");
		}
	}

}
